package br.edu.ufcg.greengrid.util;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

public class OutputLazyList<E> extends InputLazyList<E> {

	private BufferedWriter bw;

	public OutputLazyList(File file, Transform<E> transform) {
		super(file, transform);
	}

	protected void initWriter(File file) {
		try {
			this.bw = new BufferedWriter(new FileWriter((file)));
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
	}

	@Override
	public boolean add(E e) {
		if(this.bw == null){
			initWriter(this.file);
		}
		try {
			this.bw.write(this.transform.to(e));
			this.bw.newLine();
			return true;
		} catch (Exception ex) {
			throw new RuntimeException(ex);
		}
	}

	public void close() {
		super.close();
		if (this.bw != null) {
			try {
				this.bw.close();
			} catch (IOException e) {
				throw new RuntimeException(e);
			}
		}
	}

}